package com.xh.bussiness.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xh.bussiness.permission.model.User;
import com.xh.bussiness.permission.service.IUserService;
import com.xh.bussiness.permission.util.UserAuthUtil;
import com.xh.bussiness.system.bean.dto.StudentBean;
import com.xh.bussiness.system.bean.dto.StudentDto;
import com.xh.bussiness.system.bean.request.StudentRequest;
import com.xh.bussiness.system.dao.StudentMapper;
import com.xh.bussiness.system.model.Parent;
import com.xh.bussiness.system.model.ParentStudent;
import com.xh.bussiness.system.model.Student;
import com.xh.bussiness.system.model.UserStudent;
import com.xh.bussiness.system.service.IParentService;
import com.xh.bussiness.system.service.IParentStudentService;
import com.xh.bussiness.system.service.IStudentService;
import com.xh.bussiness.system.service.IUserStudentService;
import com.xh.bussiness.thirdapi.LongwenApi;
import com.xh.bussiness.tms.model.ClassStudent;
import com.xh.bussiness.tms.service.IClassStudentService;
import com.xh.core.bean.XhPage;
import com.xh.core.exception.XhException;
import com.xh.core.service.impl.BaseServiceImpl;
import com.xh.core.util.DateUtils;
import com.xh.core.util.MD5Utils;
import com.xh.core.util.ObjectUtils;
import com.xh.core.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

@Service
public class StudentServiceImpl extends BaseServiceImpl<StudentMapper, Student> implements IStudentService {

    private Logger log = LoggerFactory.getLogger(StudentServiceImpl.class);

    @Autowired
    private IUserService userService;
    @Autowired
    private IParentService parentService;
    @Autowired
    private IParentStudentService parentStudentService;
    @Autowired
    private IClassStudentService classStudentService;
    @Autowired
    private IUserStudentService userStudentService;

    @Override
    public List<Student> getStudentByUserId(String userId) {
        QueryWrapper qw = new QueryWrapper<Student>();
        qw.in("user_id", userId);
        return this.dao.selectList(qw);
    }

    @Override
    public XhPage queryStudentPage(XhPage page, StudentRequest bean) {
        QueryWrapper qw = new QueryWrapper<Student>();
        //拼装条件
        qw = prepareParams(bean, qw);
        qw.orderByDesc("create_time");
        return (XhPage) this.dao.selectPage(page, qw);
    }

    @Override
    public List queryStudent(StudentRequest bean) {
        QueryWrapper qw = new QueryWrapper<Student>();
        //拼装条件
        qw = prepareParams(bean, qw);
        return this.selectList(qw, StudentBean.class);
    }

    @Override
    public Student queryStudentById(String id) {
        return this.getById(id);
    }

    @Override
    public Student queryStudentByLwStudentId(String lwStudentId) {
        QueryWrapper qw = new QueryWrapper();
        qw.eq("lw_student_id", lwStudentId);
        return this.dao.selectOne(qw);
    }

    @Override
    public Student addStudentByLwStudentId(String lwStudentId) {
        Map<String, Object> stuMap = LongwenApi.queryStudentInfoById(lwStudentId);
        if (stuMap == null) {
            log.error(String.format("queryStudentInfoById query result is null by:%s", lwStudentId));
            return null;
        }
        //判断家长手机号是否为空
        Object guardianTel = stuMap.get("GUARDIANTEL");
        if (guardianTel == null) {
            log.error(String.format("queryStudentInfoById guardianTel is null by:%s", lwStudentId));
            return null;
        }
        //根据家长手机号判断用户是否存在
        User user = userService.getUserByMobile(guardianTel.toString());
        if (user == null) {
            user = new User();
            user.setMobile(guardianTel.toString());
            user.setUsername(stuMap.get("GUARDIANNAME") == null ? null : stuMap.get("GUARDIANNAME").toString());
            userService.insert(user);
        }
        //保存家长信息
        Parent parent = parentService.getParentByUserId(user.getId());
        if (parent == null) {
            parent = new Parent();
            parent.setUserId(user.getId());
            parent.setName(stuMap.get("GUARDIANNAME") == null ? null : stuMap.get("GUARDIANNAME").toString());
            parentService.insertObj(parent);
        }
        Student student = initStudentByLwStuInfo(user, stuMap, lwStudentId);

        //保存学生与家长的关系
        ParentStudent parentStudent = new ParentStudent();
        parentStudent.setParentId(parent.getId());
        parentStudent.setStudentId(student.getId());
        parentStudent.setRelation(stuMap.get("RELATION") == null ? null : stuMap.get("RELATION").toString());
        parentStudentService.insert(parentStudent);

        return student;
    }

    @Override
    public Student initStudentByLwStuInfo(User user, Map<String, Object> studentMap, Object id) {
        Student student = new Student();
        student.setUserId(user.getId());
        student.setLwStudentId(id.toString());
        Object name = studentMap.get("NAME");
        if (name != null) {
            student.setName(name.toString());
        }
        Object sex = studentMap.get("SEX");
        if (sex != null) {
            //龙文学生性别为2则女
            if (sex.toString().equals("2")) {
                student.setSex(0);
            } else {
                student.setSex(1);
            }
        }
        Object schoolId = studentMap.get("SCHOOLID");
        if (schoolId != null) {
            student.setLwSchoolId(schoolId.toString());
        }
        Object schoolName = studentMap.get("WAREHOUSENAME");
        if (schoolName != null) {
            student.setLwSchoolName(schoolName.toString());
        }
        this.insert(student);
        return student;
    }

    @Override
    public void addStudent(StudentBean studentBean) {
        //判断家长手机号是否为空
        String motherPhone = studentBean.getMotherPhone();
        Student student = new Student();
        ObjectUtils.copyNonNullProperties(studentBean, student);
        if (!StringUtils.isEmpty(studentBean.getBirthday())) {
            student.setBirthday(DateUtils.date2LocalDate(DateUtils.parse(studentBean.getBirthday(), "yyyy-MM-dd")));
        }
        List<String> classIds = studentBean.getClassIds();
//        if (CollectionUtils.isEmpty(classIds)) {
//            student.setStatus(0);
//        }else{
//            student.setStatus(1);
//        }
        student.setStatus(1);
        if (StringUtils.isNotEmpty(studentBean.getThirdId())) {
            student.setId(studentBean.getThirdId());
        }
        super.insert(student);

        User user = userService.getUserByMobile(motherPhone);
        if (user == null) {
            user = new User();
            user.setMobile(motherPhone);
            user.setUsername("家长");
            userService.insert(user);
            user.setPassword(UserAuthUtil.encodePassword(user.getId(), MD5Utils.string2MD5(user.getMobile())));
            userService.update(user);
        }
        student.setUserId(user.getId());
        super.update(student);
//        UserStudent userStudent = new UserStudent();
//        userStudent.setUserId(user.getId());
//        userStudent.setStudentId(student.getId());
//        userStudentService.insert(userStudent);

        if (CollectionUtils.isEmpty(classIds)) {
            return;
        }
        for (String classId : classIds) {
            ClassStudent classStudent = new ClassStudent();
            classStudent.setClassId(classId);
            classStudent.setStudentId(student.getId());
            classStudentService.insert(classStudent);
        }
    }

    @Override
    public void saveOrUpadte(StudentBean studentBean) {
        Student student = new Student();
        ObjectUtils.copyNonNullProperties(studentBean, student);
        if (!StringUtils.isEmpty(studentBean.getBirthday())) {
            student.setBirthday(DateUtils.date2LocalDate(DateUtils.parse(studentBean.getBirthday(), "yyyyMMdd")));
        }
        Student exist = super.getById(student.getId());
        if(exist == null){
            super.insert(student);
        }
        String motherPhone = studentBean.getMotherPhone();
        User user = null;
        if(StringUtils.isNotEmpty(motherPhone)){
            user = userService.getUserByMobile(motherPhone);
            if (user == null) {
                user = new User();
                user.setId(student.getId());
                user.setMobile(motherPhone);
                user.setUsername("家长");
                user.setSysUser(0);
                user.setPassword(UserAuthUtil.encodePassword(user.getId(), MD5Utils.string2MD5(user.getMobile())));
                userService.insert(user);
            }
            student.setUserId(user.getId());
        }
        super.update(student);
    }

    @Override
    public Student queryStudentByThridId(String thirdId) {
        QueryWrapper qw = new QueryWrapper();
        qw.eq("third_id", thirdId);
        return this.selectFirst(qw);
    }

    @Override
    public List<Student> queryByName(String name) {
        QueryWrapper qw = new QueryWrapper();
        if(StringUtils.isNotEmpty(name)) {
            qw.like("name", name);
        }
        return super.queryByCondition(qw);
    }

//    private void saveOrUpdateParent(StudentBean studentBean){
//        String stuPhone = studentBean.getPhone();
//        User user = null;
//        if(StringUtils.isNotEmpty(stuPhone)){
//            user = userService.getUserByMobile(stuPhone);
//            if (user == null) {
//                user = new User();
//                user.setMobile(stuPhone);
//                user.setUsername("家长");
//                userService.insert(user);
//                user.setPassword(UserAuthUtil.encodePassword(user.getId(), MD5Utils.string2MD5(user.getMobile())));
//                userService.update(user);
//            }
//        }
//        String motherPhone = studentBean.getMotherPhone();
//        if(StringUtils.isNotEmpty(motherPhone)){
//            user = userService.getUserByMobile(motherPhone);
//            if (user == null) {
//                user = new User();
//                user.setMobile(motherPhone);
//                user.setUsername("母亲");
//                userService.insert(user);
//                user.setPassword(UserAuthUtil.encodePassword(user.getId(), MD5Utils.string2MD5(user.getMobile())));
//                userService.update(user);
//            }
//        }
//        String fatherPhone = studentBean.getFatherPhone();
//        if(StringUtils.isNotEmpty(fatherPhone)){
//            user = userService.getUserByMobile(fatherPhone);
//            if (user == null) {
//                user = new User();
//                user.setMobile(motherPhone);
//                user.setUsername("父亲");
//                userService.insert(user);
//                user.setPassword(UserAuthUtil.encodePassword(user.getId(), MD5Utils.string2MD5(user.getMobile())));
//                userService.update(user);
//            }
//        }
//    }

    @Override
    public void updateStudent(StudentBean studentBean) {
        Student student = new Student();
        ObjectUtils.copyNonNullProperties(studentBean, student);
        if (!StringUtils.isEmpty(studentBean.getBirthday())) {
            student.setBirthday(DateUtils.date2LocalDate(DateUtils.parse(studentBean.getBirthday(), "yyyy-MM-dd")));
        }
        List<String> classIds = studentBean.getClassIds();
//        if (CollectionUtils.isEmpty(classIds)) {
//            student.setStatus(0);
//        }else{
//            student.setStatus(1);
//        }
        super.update(student);
        if (!StringUtils.isEmpty(student.getUserId())) {
            User user = userService.getById(student.getUserId());
            if (user != null) {
                //不为系统用户修改手机号
                if (user.getSysUser() == null || 1 !=user.getSysUser()) {
                    user.setMobile(student.getFatherPhone());
                    userService.update(user);
                }
            }
        }else {
            User user = userService.getUserByMobile(student.getMotherPhone());
            if (user == null) {
                user = new User();
                user.setMobile(student.getMotherPhone());
                user.setUsername("家长");
                userService.insert(user);
                user.setPassword(UserAuthUtil.encodePassword(user.getId(), MD5Utils.string2MD5(user.getMobile())));
                userService.update(user);
            }
            student.setUserId(user.getId());
            super.update(student);
        }

        ClassStudent classStudentBean = new ClassStudent();
        classStudentBean.setStudentId(studentBean.getId());
        classStudentService.deleteStudentOrClassByClassIdOrStuId(classStudentBean);
        if (CollectionUtils.isEmpty(classIds)) {
            return;
        }
        for (String classId : classIds) {
            ClassStudent classStudent = new ClassStudent();
            classStudent.setClassId(classId);
            classStudent.setStudentId(student.getId());
            classStudentService.insert(classStudent);
        }
    }

    @Override
    public List<StudentDto> queryByStatus(String classId, String name, Integer groupStatus) {
        QueryWrapper qw = new QueryWrapper<Student>();
        if(groupStatus != null){
            qw.eq("group_status",groupStatus);
        }
        qw.eq("status",1);
        if (StringUtils.isNotEmpty(name)) {
            qw.like("name",name);
        }
        List<StudentDto> list = super.selectList(qw,StudentDto.class);
        QueryWrapper<ClassStudent> csQw = new QueryWrapper<ClassStudent>();
        csQw.eq("class_id",classId);
        List<ClassStudent> classStudents = classStudentService.queryByCondition(csQw);
        List<String> studentIds = classStudents.stream().map(ClassStudent :: getStudentId).collect(Collectors.toList());
        for (StudentDto studentDto : list) {
            if (studentIds.contains(studentDto.getId())) {
                studentDto.setInCurrentClass(1);
            }else{
                studentDto.setInCurrentClass(0);
            }
        }
        return list;
    }

    @Override
    public List<StudentDto> queryStudentByClassId(String classId) {
        List<StudentDto> studentDtos = classStudentService.queryStudentByClassId(classId);
        return studentDtos;
    }

    @Override
    public List<Student> queryByUserId(String userId) {
        QueryWrapper qw = new QueryWrapper<Student>();
        if (StringUtils.isNotEmpty(userId)) {
            qw.eq("user_id",userId);
        }
        return super.queryByCondition(qw);
    }

    /**
     * 准备条件
     *
     * @param bean
     * @param qw
     */
    private QueryWrapper prepareParams(StudentRequest bean, QueryWrapper qw) {
        if (bean.getIds() != null && bean.getIds().length > 0) {
            qw.in("id", bean.getIds());
        }
        if (!StringUtils.isEmpty(bean.getUserId())) {
            qw.eq("user_id", bean.getUserId());
        }
        if (!StringUtils.isEmpty(bean.getName())) {
            qw.like("name", bean.getName());
        }
        if (!StringUtils.isEmpty(bean.getBirthday())) {
            qw.eq("birthday", bean.getBirthday());
        }
        if (bean.getSex() != null) {
            qw.eq("sex", bean.getSex());
        }
        if (!StringUtils.isEmpty(bean.getGradeId())) {
            qw.eq("grade_id", bean.getGradeId());
        }
        if (!StringUtils.isEmpty(bean.getMobile())) {
            qw.eq("mother_phone", bean.getMobile());
        }
        if (bean.getGroupStatus() != null) {
            qw.eq("group_status", bean.getGroupStatus());
        }
        qw.eq("intention_status", 0);
        return qw;
    }
}
